%%% ------------------------------------------------------------------
%%% Licensed under the Apache License, Version 2.0 (the 'License');
%%%  you may not use this file except in compliance with the License.
%%%  You may obtain a copy of the License at
%%%
%%%      http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Copyright (c) 2017 qingchuwudi <bypf2009@vip.qq.com>
%%%
%%%  Unless required by applicable law or agreed to in writing, software
%%%  distributed under the License is distributed on an 'AS IS' BASIS,
%%%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%%  See the License for the specific language governing permissions and
%%%  limitations under the License.
%%%
%%% @doc
%%% @author  qingchuwudi <'bypf2009@vip.qq.com'>
%%% @copyright 2017 qingchuwudi <bypf2009@vip.qq.com>
%%% @end
%%% created|changed : 2017-09-12 15:00
%%% coding : utf-8
%%% ------------------------------------------------------------------
-module(elcache_ts0).
-author("qingchuwudi").

-behaviour(gen_server).
-export([
    start_link/0,
    add_ts/1,
    send_msg/1
]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-export ([start_cache/0, mfoldl/1]).

%% -----------------------------
%%    对外api
%% -----------------------------

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, {}, []).

add_ts(Count) when is_integer(Count) andalso Count > 0 ->
    gen_server:cast(?MODULE, {add_ts, Count}).

send_msg(Gap) when is_integer(Gap) andalso Gap >= 0 ->
    gen_server:cast(?MODULE, {send_msg, Gap}).


start_cache() ->
    elcache:add_pool(test, 10, 100, 30000, fun elcache_ts0:mfoldl/1).

mfoldl([_|_] = DataList) ->
    mfoldl(DataList, 0).
mfoldl([_|T], C) ->
    mfoldl(T, C + 1);
mfoldl([], C) ->
    io:format("-- handle [~p] messages --.~n",[C]),
    C.

handle_send(0, [Pid | T]) ->
    elcache_ts:send_msg(Pid),
    handle_send(0, T);
handle_send(_, []) ->
    ok;
handle_send(Gap, [Pid | Pids]) ->
    %% 10 means 10 msg/ms.
    % Pids2 = handle_send2(10, Pids),
    elcache_ts:send_msg(Pid),
    timer:sleep(Gap),
    handle_send(Gap, Pids).

%% -----------------------------
%%    回调函数
%% -----------------------------

%% 初始化
init({}) ->
    {ok, []}.

%% 同步
handle_call(_Request, _From, State) ->
    {reply, {error, unknown_call}, State}.

%% 异步
handle_cast({add_ts, Count}, State) ->
    Fun = fun
        F(0, Pids) ->
            Pids;
        F(TCount, Pids) ->
            {ok, Pid} = elcache_ts:start_link(),
            F(TCount - 1, [Pid | Pids])
    end,
    Pids2 = Fun(Count, State),
    {noreply, Pids2};

handle_cast({send_msg, Gap}, State) ->
    handle_send(Gap, State),
    io:format("[~p] messages send done!~n",[length(State)]),
    {noreply, State};

handle_cast(_Msg, State) ->
    {noreply, State}.

%% 消息
handle_info(_Info, State) ->
    {noreply, State}.

%% 终止处理
terminate(_Reason, _State) ->
    ok.

%% 热更替换
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.
